<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>充电选择 - TGPay IoT 充电桩</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        
        .header {
            background: linear-gradient(135deg, #00c851, #00a843);
            color: white;
            padding: 15px 20px;
            position: relative;
            box-shadow: 0 2px 10px rgba(0, 200, 81, 0.3);
        }
        
        .header .back-btn {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
        }
        
        .header .title {
            text-align: center;
            font-size: 18px;
            font-weight: 500;
        }
        
        .header .menu-btn {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
        }
        
        .device-info {
            background: white;
            margin: 15px;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            position: relative;
        }
        
        .device-info .location {
            color: #00c851;
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }
        
        .device-info .location::before {
            content: "📍";
            margin-right: 8px;
        }
        
        .device-info .device-id {
            color: #666;
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        .contact-btn {
            position: absolute;
            right: 20px;
            top: 20px;
            background: #00c851;
            color: white;
            border: none;
            border-radius: 20px;
            padding: 8px 15px;
            font-size: 12px;
            cursor: pointer;
        }
        
        .section {
            background: white;
            margin: 15px;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .section-title {
            color: #00c851;
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }
        
        .section-title::before {
            content: "";
            width: 4px;
            height: 16px;
            background: #00c851;
            margin-right: 10px;
            border-radius: 2px;
        }
        
        .charge-options {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .charge-option {
            padding: 15px 10px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }
        
        .charge-option.selected {
            border-color: #00c851;
            background: #00c851;
            color: white;
        }
        
        .charge-option .amount {
            font-size: 16px;
            font-weight: bold;
        }
        
        .custom-amount {
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            background: white;
            color: #666;
        }
        
        .pricing-info {
            margin-top: 20px;
        }
        
        .pricing-tabs {
            display: flex;
            border-bottom: 1px solid #e0e0e0;
            margin-bottom: 15px;
        }
        
        .pricing-tab {
            flex: 1;
            padding: 10px;
            text-align: center;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s ease;
        }
        
        .pricing-tab.active {
            color: #00c851;
            border-bottom-color: #00c851;
        }
        
        .pricing-content {
            padding: 15px 0;
        }
        
        .pricing-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .pricing-row:last-child {
            border-bottom: none;
        }
        
        .start-btn {
            width: 100%;
            padding: 15px;
            background: #00c851;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            margin: 20px 0;
            transition: background 0.3s ease;
        }
        
        .start-btn:hover {
            background: #00a843;
        }
        
        .start-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
            color: #666;
        }
        
        .error {
            background: #ffe6e6;
            color: #d32f2f;
            padding: 15px;
            border-radius: 8px;
            margin: 15px;
            display: none;
        }
        
        .success {
            background: #e8f5e8;
            color: #2e7d32;
            padding: 15px;
            border-radius: 8px;
            margin: 15px;
            display: none;
        }
        
        /* 充电状态界面 */
        .charging-status {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: white;
            z-index: 1000;
        }
        
        .charging-status.active {
            display: block;
        }
        
        .charging-header {
            background: linear-gradient(135deg, #00c851, #00a843);
            color: white;
            padding: 15px 20px;
            position: relative;
            box-shadow: 0 2px 10px rgba(0, 200, 81, 0.3);
        }
        
        .charging-header .back-btn {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
        }
        
        .charging-header .title {
            text-align: center;
            font-size: 18px;
            font-weight: 500;
        }
        
        .charging-info {
            padding: 20px;
        }
        
        .order-info {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        
        .order-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .order-row:last-child {
            border-bottom: none;
        }
        
        .order-label {
            color: #666;
            font-size: 14px;
        }
        
        .order-value {
            color: #333;
            font-size: 14px;
            font-weight: 500;
        }
        
        .charging-progress {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            text-align: center;
        }
        
        .progress-title {
            color: #00c851;
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 15px;
        }
        
        .progress-circle {
            width: 120px;
            height: 120px;
            border: 8px solid #f0f0f0;
            border-top: 8px solid #00c851;
            border-radius: 50%;
            margin: 0 auto 15px;
            animation: spin 2s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .progress-text {
            color: #333;
            font-size: 18px;
            font-weight: bold;
        }
        
        .stop-btn {
            width: 100%;
            padding: 15px;
            background: #f44336;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            margin: 20px 0;
            transition: background 0.3s ease;
        }
        
        .stop-btn:hover {
            background: #d32f2f;
        }
        
        /* 响应式设计 */
        @media (max-width: 480px) {
            .charge-options {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <button class="back-btn" onclick="history.back()">✕</button>
        <div class="title">充电选择</div>
        <button class="menu-btn">⋯</button>
    </div>
    
    <div class="device-info">
        <div class="location" id="deviceLocation">加载中...</div>
        <div class="device-id">设备ID: <span id="deviceId">加载中...</span></div>
        <button class="contact-btn">试运营阶段</button>
    </div>
    
    <div class="section">
        <div class="section-title">计费方式</div>
        <div class="charge-options" id="chargeOptions">
            <div class="charge-option selected" data-type="3" data-amount="240">
                <div class="amount">免费充电4小时</div>
            </div>
            <div class="charge-option" data-type="2" data-amount="100" style="pointer-events: none; opacity: 0.5; cursor: not-allowed;">
                <div class="amount">1元</div>
            </div>
            <div class="charge-option" data-type="2" data-amount="200" style="pointer-events: none; opacity: 0.5; cursor: not-allowed;">
                <div class="amount">2元</div>
            </div>
            <div class="charge-option" data-type="2" data-amount="300" style="pointer-events: none; opacity: 0.5; cursor: not-allowed;">
                <div class="amount">3元</div>
            </div>
            <div class="charge-option" data-type="2" data-amount="400" style="pointer-events: none; opacity: 0.5; cursor: not-allowed;">
                <div class="amount">4元</div>
            </div>
            <div class="charge-option" data-type="2" data-amount="500" style="pointer-events: none; opacity: 0.5; cursor: not-allowed;">
                <div class="amount">5元</div>
            </div>
        </div>
        <div class="custom-amount" onclick="showCustomAmount()" style="pointer-events: none; opacity: 0.5; cursor: not-allowed;">
            自定义金额
        </div>
    </div>
    
    <div class="section">
        <div class="section-title">计费说明</div>
        <div class="pricing-info">
            <div class="pricing-tabs">
                <div class="pricing-tab active" data-tab="electricity">电费</div>
                <div class="pricing-tab" data-tab="service">服务费</div>
            </div>
            <div class="pricing-content">
                <div class="pricing-row">
                    <span>时段</span>
                    <span>电费(元/度)</span>
                </div>
                <div class="pricing-row" id="pricingDetails">
                    <span>00:00-23:59</span>
                    <span>试运营期间免费充电</span>
                </div>
            </div>
        </div>
    </div>
    
    <div class="error" id="errorMessage"></div>
    <div class="success" id="successMessage"></div>
    
    <button class="start-btn" id="startBtn" onclick="startCharging()">
        开始充电
    </button>
    
    <!-- 充电状态界面 -->
    <div class="charging-status" id="chargingStatus">
        <div class="charging-header">
            <button class="back-btn" onclick="hideChargingStatus()">←</button>
            <div class="title">充电中</div>
        </div>
        
        <div class="charging-info">
            <div class="order-info">
                <div class="order-row">
                    <span class="order-label">订单号</span>
                    <span class="order-value" id="orderNumber">-</span>
                </div>
                <div class="order-row">
                    <span class="order-label">设备编号</span>
                    <span class="order-value" id="chargingDeviceId">-</span>
                </div>
                <div class="order-row">
                    <span class="order-label">充电端口</span>
                    <span class="order-value" id="chargingPort">-</span>
                </div>
                <div class="order-row">
                    <span class="order-label">充电模式</span>
                    <span class="order-value" id="chargingMode">-</span>
                </div>
                <div class="order-row">
                    <span class="order-label">开始时间</span>
                    <span class="order-value" id="startTime">-</span>
                </div>
            </div>
            
            <div class="charging-progress">
                <div class="progress-title">充电进行中</div>
                <div class="progress-circle"></div>
                <div class="progress-text">正在充电...</div>
            </div>
            
            <button class="stop-btn" onclick="stopCharging()">
                停止充电
            </button>
        </div>
    </div>
    
    <script>
        // API配置 - 动态获取当前主机地址，支持其他设备访问
        const API_BASE_URL = `${window.location.protocol}//${window.location.host}/api`;
        
        // 当前状态
        let currentDevice = null;
        let selectedPort = null; // 只通过URL参数获取端口
        let selectedChargeType = 3; // 默认按时间计费
        let selectedAmount = 240; // 默认4小时（240分钟）
        
        /**
         * 为URL添加随机数参数以避免缓存
         * @param {string} url 原始URL
         * @returns {string} 添加了随机数参数的URL
         */
        function addCacheBuster(url) {
            const separator = url.includes('?') ? '&' : '?';
            return `${url}${separator}_t=${Date.now()}&_r=${Math.random().toString(36).substr(2, 9)}`;
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializePage();
            bindEvents();
            loadDeviceFromUrl();
        });
        
        function initializePage() {
            // 加载充电配置
            loadChargingConfig();
            // 直接启用开始充电按钮
            document.getElementById('startBtn').disabled = false;
            document.getElementById('startBtn').textContent = '开始充电';
        }
        
        /**
         * 加载充电配置
         */
        function loadChargingConfig() {
            fetch(addCacheBuster(`${API_BASE_URL}/charging/config`))
                .then(response => response.json())
                .then(result => {
                    if (result.code === 0 && result.data) {
                        const config = result.data;
                        // 更新默认充电时长
                        selectedAmount = config.defaultDuration;
                        
                        // 更新充电选项显示
                        const chargeOption = document.querySelector('.charge-option[data-type="3"]');
                        if (chargeOption) {
                            const hours = Math.floor(config.defaultDuration / 60);
                            const minutes = config.defaultDuration % 60;
                            let timeText = '';
                            if (hours > 0) {
                                timeText += `${hours}小时`;
                            }
                            if (minutes > 0) {
                                timeText += `${minutes}分钟`;
                            }
                            chargeOption.querySelector('.amount').textContent = `免费充电${timeText}`;
                            chargeOption.dataset.amount = config.defaultDuration;
                        }
                        
                        console.log('充电配置加载成功:', config);
                    } else {
                        console.warn('加载充电配置失败，使用默认值');
                    }
                })
                .catch(error => {
                    console.error('加载充电配置失败:', error);
                });
        }
        
        function bindEvents() {
            // 绑定计费方式选择事件
            document.querySelectorAll('.charge-option').forEach(option => {
                option.addEventListener('click', function() {
                    // 只有充满自停选项可点击
                    if (this.dataset.type !== '1') {
                        return;
                    }
                    document.querySelectorAll('.charge-option').forEach(opt => opt.classList.remove('selected'));
                    this.classList.add('selected');
                    selectedChargeType = parseInt(this.dataset.type);
                    selectedAmount = parseInt(this.dataset.amount);
                });
            });
            
            // 绑定计费说明标签切换事件
            document.querySelectorAll('.pricing-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.pricing-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    const tabType = this.dataset.tab;
                    updatePricingContent(tabType);
                });
            });
        }
        
        function updatePricingContent(tabType) {
            const pricingDetails = document.getElementById('pricingDetails');
            if (tabType === 'electricity') {
                pricingDetails.innerHTML = `
                    <span>00:00-23:59</span>
                    <span>试运营期间免费充电</span>
                `;
            } else {
                pricingDetails.innerHTML = `
                    <span>服务费率</span>
                    <span>试运营期间免费充电</span>
                `;
            }
        }
        
        /**
         * 获取URL参数
         * @returns {Object} URL参数对象
         */
        function getUrlParams() {
            const params = {};
            const urlSearchParams = new URLSearchParams(window.location.search);
            for (const [key, value] of urlSearchParams) {
                params[key] = decodeURIComponent(value);
            }
            return params;
        }
        
        /**
         * 从URL参数加载设备信息
         */
        function loadDeviceFromUrl() {
            const urlParams = getUrlParams();
            const deviceId = urlParams.deviceId || urlParams.imei;
            const deviceName = urlParams.deviceName || urlParams.name;
            const portId = urlParams.portId || urlParams.port;
            
            if (deviceId) {
                // 如果URL中有设备ID，直接使用该设备
                currentDevice = {
                    imei: deviceId,
                    name: deviceName || `设备-${deviceId}`
                };
                updateDeviceInfo(currentDevice, deviceName);
                
                // 如果URL中指定了端口号，预选该端口
                if (portId) {
                    selectedPort = parseInt(portId);
                }
                
                loadDeviceDetail(deviceId);
            } else {
                // 如果URL中没有设备ID，则加载设备列表
                loadDeviceList();
            }
        }
        
        /**
         * 加载设备列表（备用方法）
         */
        function loadDeviceList() {
            fetch(addCacheBuster(`${API_BASE_URL}/devices`))
                .then(response => response.json())
                .then(result => {
                    if (result.code === 0 && result.data && result.data.length > 0) {
                        // 使用第一个设备作为演示
                        currentDevice = result.data[0];
                        updateDeviceInfo(currentDevice);
                        loadDeviceDetail(currentDevice.imei);
                    } else {
                        showError('未找到可用设备');
                    }
                })
                .catch(error => {
                    console.error('加载设备列表失败:', error);
                    showError('加载设备列表失败');
                });
        }
        
        /**
         * 更新设备信息显示
         * @param {Object} device 设备对象
         * @param {string} customName 自定义设备名称（可选）
         */
        function updateDeviceInfo(device, customName) {
            const deviceName = customName || device.name || `中间南侧-${device.imei.slice(-1)}号设备`;
            document.getElementById('deviceLocation').textContent = deviceName;
            document.getElementById('deviceId').textContent = device.imei;
        }
        
        function loadDeviceDetail(imei) {
            // 设备详情加载已简化，因为不再需要端口选择
            console.log('设备详情加载完成:', imei);
            
            // 页面刷新后检查设备状态
            checkDeviceStatusOnLoad(imei);
        }
        
        /**
         * 页面加载时检查设备状态
         * @param {string} imei 设备IMEI
         */
        function checkDeviceStatusOnLoad(imei) {
            if (!selectedPort) {
                console.log('未指定端口号，跳过状态查询');
                return;
            }
            
            // 同时检查上游状态和本地充电订单状态
            Promise.all([
                fetch(addCacheBuster(`${API_BASE_URL}/devices/${imei}/status`)).then(r => r.json()),
                fetch(addCacheBuster(`${API_BASE_URL}/charging/orders?imei=${imei}&portId=${selectedPort}&status=1`)).then(r => r.json())
            ])
                .then(([deviceResult, orderResult]) => {
                    console.log('设备状态查询结果:', deviceResult);
                    console.log('本地订单查询结果:', orderResult);
                    
                    let orderNo = null;
                    let hasActiveCharging = false;
                    
                    // 首先检查上游状态
                    if (deviceResult.code === 0 && deviceResult.data) {
                        const deviceData = deviceResult.data.data || deviceResult.data;
                        const portIndex = selectedPort - 1;
                        
                        if (deviceData.portStatus && deviceData.portStatus[portIndex] === 1) {
                            orderNo = deviceData.portOrderIds ? deviceData.portOrderIds[portIndex] : null;
                            hasActiveCharging = true;
                            console.log('上游检测到端口', selectedPort, '正在充电，订单号:', orderNo);
                        }
                    }
                    
                    // 如果上游没有检测到充电，检查本地数据库
                    if (!hasActiveCharging && orderResult.code === 0 && orderResult.data && orderResult.data.length > 0) {
                        const localOrder = orderResult.data[0]; // 取最新的订单
                        orderNo = localOrder.orderNo;
                        hasActiveCharging = true;
                        console.log('本地检测到端口', selectedPort, '正在充电，订单号:', orderNo);
                    }
                    
                    // 如果检测到有充电订单，获取详细信息并显示
                    if (hasActiveCharging && orderNo) {
                        fetch(addCacheBuster(`${API_BASE_URL}/charging/status?orderNo=${orderNo}`))
                            .then(response => response.json())
                            .then(statusResult => {
                                if (statusResult.code === 0 && statusResult.data) {
                                    console.log('获取到真实订单信息:', statusResult.data);
                                    
                                    // 更新当前状态
                                    window.currentOrder = statusResult.data;
                                    
                                    // 显示充电状态界面
                                    showChargingStatus(statusResult.data);
                                } else {
                                    console.warn('获取订单状态失败，使用基本信息:', statusResult.message);
                                    
                                    // 如果获取订单状态失败，使用基本信息
                                    const orderData = {
                                        orderNo: orderNo,
                                        status: 1,
                                        startTime: new Date(),
                                        chargeType: 1,
                                        amount: 0
                                    };
                                    
                                    window.currentOrder = orderData;
                                    showChargingStatus(orderData);
                                }
                            })
                            .catch(error => {
                                console.error('获取订单状态失败:', error);
                                
                                // 如果请求失败，使用基本信息
                                const orderData = {
                                    orderNo: orderNo,
                                    status: 1,
                                    startTime: new Date(),
                                    chargeType: 1,
                                    amount: 0
                                };
                                
                                window.currentOrder = orderData;
                                showChargingStatus(orderData);
                            });
                    } else {
                        console.log('未检测到正在进行的充电');
                    }
                })
                .catch(error => {
                    console.error('查询状态失败:', error);
                });
        }
        

        
        function showCustomAmount() {
            const amount = prompt('请输入充电金额(元):', '10');
            if (amount && !isNaN(amount) && parseFloat(amount) > 0) {
                selectedChargeType = 2; // 按金额
                selectedAmount = Math.round(parseFloat(amount) * 100); // 转换为分
                
                // 取消其他选项的选中状态
                document.querySelectorAll('.charge-option').forEach(opt => opt.classList.remove('selected'));
                
                // 显示自定义金额
                document.querySelector('.custom-amount').innerHTML = `自定义: ${amount}元`;
                document.querySelector('.custom-amount').style.borderColor = '#00c851';
                document.querySelector('.custom-amount').style.background = '#f0fff4';
            }
        }
        
        function startCharging() {
            if (!currentDevice) {
                showError('请先选择设备');
                return;
            }
            
            if (!selectedPort) {
                showError('请在URL中指定端口号（portId参数）');
                return;
            }
            
            const startBtn = document.getElementById('startBtn');
            startBtn.disabled = true;
            startBtn.textContent = '启动中...';
            
            const requestData = {
                imei: currentDevice.imei,
                portId: parseInt(selectedPort),
                chargeType: selectedChargeType,
                chargeParam: selectedAmount,
                startMethod: 1, // 扫码启动
                cardNumber: 0,
                availableAmount: selectedAmount
            };
            
            fetch(addCacheBuster(`${API_BASE_URL}/charging/start`), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 0) {
                    showSuccess('充电启动成功！');
                    // 显示充电状态界面
                    showChargingStatus(result.data);
                } else {
                    showError(result.message || '启动充电失败');
                }
            })
            .catch(error => {
                console.error('启动充电失败:', error);
                showError('启动充电失败，请重试');
            })
            .finally(() => {
                startBtn.disabled = false;
                startBtn.textContent = '开始充电';
            });
        }
        
        // 显示充电状态界面
        function showChargingStatus(orderData) {
            // 更新订单信息
            const orderNo = orderData?.orderNo || orderData?.data?.orderNo || (new Date().getTime().toString());
            document.getElementById('orderNumber').textContent = orderNo;
            document.getElementById('chargingDeviceId').textContent = currentDevice.imei;
            document.getElementById('chargingPort').textContent = `端口 ${String.fromCharCode(64 + selectedPort)}`;
            
            // 显示充电模式
            let modeText = '';
            const chargeType = orderData?.chargeType || selectedChargeType;
            const amount = orderData?.amount || selectedAmount;
            
            if (chargeType === 1 || chargeType === 3) {
                modeText = '充满自停';
            } else {
                modeText = `${amount / 100}元`;
            }
            document.getElementById('chargingMode').textContent = modeText;
            
            // 显示开始时间
            let startTime = orderData?.startTime;
            if (!startTime) {
                // 如果没有开始时间，尝试从嵌套的data中获取
                startTime = orderData?.data?.startTime;
            }
            if (!startTime) {
                // 如果仍然没有，使用当前时间作为fallback
                startTime = new Date();
                console.warn('未获取到真实开始时间，使用当前时间');
            } else if (typeof startTime === 'string') {
                startTime = new Date(startTime);
            } else if (Array.isArray(startTime)) {
                // 处理LocalDateTime的数组格式 [year, month, day, hour, minute, second]
                startTime = new Date(startTime[0], startTime[1] - 1, startTime[2], startTime[3], startTime[4], startTime[5]);
            }
            
            const timeStr = startTime.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
            document.getElementById('startTime').textContent = timeStr;
            
            // 显示充电状态界面
            document.getElementById('chargingStatus').classList.add('active');
            
            // 存储当前订单信息
            window.currentOrder = orderData;
        }
        
        // 隐藏充电状态界面
        function hideChargingStatus() {
            document.getElementById('chargingStatus').classList.remove('active');
        }
        
        // 停止充电
        function stopCharging() {
            if (!window.currentOrder) {
                showError('没有正在进行的充电订单');
                return;
            }
            
            if (!confirm('确定要停止充电吗？')) {
                return;
            }
            
            const orderNo = window.currentOrder.orderNo || 'test-order';
            
            fetch(addCacheBuster(`${API_BASE_URL}/devices/${currentDevice.imei}/ports/${selectedPort}/stop`), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ orderNo: orderNo })
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 0) {
                    hideChargingStatus();
                    showSuccess('充电已停止');
                    window.currentOrder = null;
                } else {
                    showError(result.message || '停止充电失败');
                }
            })
            .catch(error => {
                console.error('停止充电失败:', error);
                showError('停止充电失败，请重试');
            });
        }
        
        function showError(message) {
            const errorElement = document.getElementById('errorMessage');
            errorElement.textContent = message;
            errorElement.style.display = 'block';
            setTimeout(() => {
                errorElement.style.display = 'none';
            }, 3000);
        }
        
        function showSuccess(message) {
            const successElement = document.getElementById('successMessage');
            successElement.textContent = message;
            successElement.style.display = 'block';
            setTimeout(() => {
                successElement.style.display = 'none';
            }, 3000);
        }
    </script>
</body>
</html>